package com.hmdp.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.RedisData;
import com.hmdp.entity.Shop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

@Component
@Slf4j

public class CacheClient {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    public void set(String key, Object value, Long time , TimeUnit unit){
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value),time,unit);


    }
    public void setWithLogicalExpire(String key, Object value, Long time , TimeUnit unit){
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));

        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));


    }
    public <R, ID> R queryWithPassThrough(String keyPrefix, ID id , Class<R> type, Function<ID,R> dbFallback, Long time , TimeUnit unit){
        String key = keyPrefix+id;
        //先从redis查询缓存
        String shopjson = stringRedisTemplate.opsForValue().get(key);
        //判断是否存在
        System.out.println(shopjson);
        if(StrUtil.isNotBlank(shopjson)){


            return JSONUtil.toBean(shopjson,type);

//            存在返回
        }
        if (shopjson != null){
            return null;
        }

        //不存在 查询数据库
       R r =dbFallback.apply(id);
        //数据库不存在 返回错误
        if(r == null ){

            stringRedisTemplate.opsForValue().set(key,"",time, unit);
            return null;
        }
        //存在数据库 写入数据到Redis
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(r),time, unit);
        //返回
        return r;
    }
}
